package org.tea.inventory.db.service;


import org.tea.inventory.db.domain.Storage;
import org.tea.inventory.db.util.CharUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileSystemStorageService implements StorageService {

    @Autowired
    private AlumniRecordStorageService alumniRecordStorageService;

    private static String file_http_path;
    private static String file_absolute_path;
    private static Path rootLocation ;
    //= Paths.get(file_absolute_path);
    //private static final Path rootLocation = Paths.get("/home/steve/images");
    @Value("${file.absolute.path}")
    public  void setRootLocation(String file_absolute_path) {
        System.out.println("file_absolute_path"+file_absolute_path);
        FileSystemStorageService.file_absolute_path=file_absolute_path;
        FileSystemStorageService.rootLocation = Paths.get(file_absolute_path);
    }
    @Value("${file.http.path}")
    public void setFile_http_path(String file_http_path) {
        FileSystemStorageService.file_http_path = file_http_path;
    }

    private String generateUrl(String newPath,String newFileName){
        System.out.println("file_http_path"+file_http_path);
        return file_http_path+newPath+"/"+newFileName;
    }

   // private static final Path rootLocation = Paths.get("/home/steve/images");

    //private String generateUrl(String newPath,String key){
    //    return "http://xiaoyou.dgtis.com/images/"+newPath+"/"+key;
    //}

    private final String generateKey(){
        String key = null;
        Storage storageInfo = null;

        do{
            key = CharUtil.getRandomString(20);
            storageInfo = alumniRecordStorageService.findByKey(key);
        }
        while(storageInfo != null);

        return key;
    }

    public Map<String, String> storeFile(MultipartFile file) {
        Map<String, String> map = new HashMap<String, String>();

        Storage storageInfo = new Storage();
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String contentType = file.getContentType();
        String key = generateKey();
        String[] fileSuffix = originalFilename.split("\\.");
        String newFileName = key+"."+fileSuffix[fileSuffix.length-1];

        try {

            //创建目录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String ymd = sdf.format(new Date());
            String newPath = contentType.split("/")[0]+"/"+ymd;
            Path path = Files.createDirectories(FileSystemStorageService.rootLocation.resolve(newPath));
            //创建文件
            Files.copy(inputStream, path.resolve(newFileName));

            map.put("absolute_path", path+"/"+newFileName);
            //添加数据记录
            String url = generateUrl(newPath,newFileName);
            map.put("http_path", url);
            storageInfo.setOldName(originalFilename);
            storageInfo.setNewName(newFileName);
            storageInfo.setSize((int)file.getSize());
            storageInfo.setType(contentType);
            storageInfo.setFilePath("/"+newPath+"/"+newFileName);
            storageInfo.setCreateTime(LocalDateTime.now());
            storageInfo.setModifyTime(LocalDateTime.now());
            storageInfo.setKey(key);
            storageInfo.setUrl(url);
            storageInfo.setImgBelongs("");
            alumniRecordStorageService.insertSelective(storageInfo);
        }
        catch (IOException e) {
            throw new RuntimeException ("Failed to store file " + newFileName, e);
        }

        return map;
    }

    @Override
    public Storage store(MultipartFile file, String imgBelongs) {
        Storage storageInfo = new Storage();
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String contentType = file.getContentType();
        String key = generateKey();
        String[] fileSuffix = originalFilename.split("\\.");
        String newFileName = key+"."+fileSuffix[fileSuffix.length-1];

        try {

            //创建目录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String ymd = sdf.format(new Date());
            String newPath = contentType.split("/")[0]+"/"+ymd;
            Path path = Files.createDirectories(FileSystemStorageService.rootLocation.resolve(newPath));
            //创建文件
            Files.copy(inputStream, path.resolve(newFileName));


            //添加数据记录
            String url = generateUrl(newPath,newFileName);

            storageInfo.setOldName(originalFilename);
            storageInfo.setNewName(newFileName);
            storageInfo.setSize((int)file.getSize());
            storageInfo.setType(contentType);
            storageInfo.setFilePath("/"+newPath+"/"+newFileName);
            storageInfo.setCreateTime(LocalDateTime.now());
            storageInfo.setModifyTime(LocalDateTime.now());
            storageInfo.setKey(key);
            storageInfo.setUrl(url);
            storageInfo.setImgBelongs(imgBelongs);
            alumniRecordStorageService.insertSelective(storageInfo);

        }
        catch (IOException e) {
            throw new RuntimeException ("Failed to store file " + newFileName, e);
        }

        return storageInfo;
    }

    /**
     *
     * 创建文件以及添加表记录
     *
     * @param file
     */
    @Override
    public Storage store(MultipartFile file) {
        return store(file,null);
    }


    /**
     *
     * 获取文件完整的Path
     *
     * @param filePath 带有文件名的path
     * @return
     */
    @Override
    public Path load(String filePath) {
        return FileSystemStorageService.rootLocation.resolve(filePath);
    }

    /**
     * 删除文件以及表记录
     *
     * @param fileId
     */
    @Override
    public void deleteById(Integer fileId) {
        Storage storage = alumniRecordStorageService.selectByPrimaryKey(fileId);
        String filePath = storage.getFilePath().substring(1, storage.getFilePath().length());
        Path file = load(filePath);
        try {
            Files.delete(file);
            alumniRecordStorageService.deleteByPrimaryKey(fileId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取服务器文件地址全路径
     * @param filePath
     * @return
     */
    @Override
    public String loadFullFilePath(String filePath) {
        return FileSystemStorageService.file_absolute_path + filePath;
    }

}